package com.eliauk.democommon.query;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NonNull;

@Data
public class PageQuery {

    @NonNull
    @ApiModelProperty(value = "当前页数", required = true)
    private Integer currPage;

    @NonNull
    @ApiModelProperty(value = "每页大小", required = true)
    private Integer pageSize;

    private String sortBy;

    private Boolean isAsc;

    public <T> Page<T> toMpPage(OrderItem ... items){
        // 参数检查
        if (currPage <= 0 || pageSize <= 0) {
            throw new IllegalArgumentException("Invalid currSize or pageSize");
        }
        //1.分页条件
        Page<T> page = Page.of(this.currPage, this.pageSize);
        //2.1前端指定排序条件
        if (this.sortBy!=null){
            page.addOrder(new OrderItem(this.sortBy,this.isAsc));
        }
        //2.2后端查询条件
        if (items!=null){
            page.addOrder(items);
        }
        //3.查询条件由service层使用lambda处理
        return page;
    }

    public <T> Page<T> getMpPage(OrderItem items){
        return this.toMpPage(items);
    }

    //默认按照创建时间降序排序
    public <T> Page<T> createTimeDescPage() {
        return this.getMpPage(new OrderItem("create_time", false));
    }

    //默认按照创建时间降序排序
    public <T> Page<T> updateTimeDescPage() {
        return this.getMpPage(new OrderItem("update_time", false));
    }
}
